use dioxus::prelude::*;
use regex::Regex;
use serde_json::Value;
use std::sync::Arc;

use crate::components::copy::Copy;

#[component]
pub fn JsonFinder() -> Element {
    let mut json_input = use_signal(|| String::new());
    let mut query_input = use_signal(|| String::new());
    let mut query_mode = use_signal(|| "查 Key".to_string());
    let mut query_result = use_signal(Vec::<String>::new);
    let mut copy_status = use_signal(|| String::new());

    let query_mode_options = vec!["查 Key".to_string(), "查 Value".to_string()];

    // 执行搜索
    let perform_search = move |_| {
        let json = json_input.read().clone();
        let query = query_input.read().clone();
        let mode = query_mode.read().clone();

        if json.is_empty() || query.is_empty() {
            query_result.set(vec!["请输入JSON和查询内容".to_string()]);
            return;
        }

        let result = match serde_json::from_str::<Value>(&json) {
            Ok(parsed_json) => {
                let is_key_mode = mode == "查 Key";
                let mut results = Vec::new();
                find_paths(
                    &parsed_json,
                    "data".to_string(),
                    &query,
                    is_key_mode,
                    &mut results,
                );

                if results.is_empty() {
                    vec!["未找到匹配项".to_string()]
                } else {
                    results
                }
            }
            Err(_) => vec!["无效的JSON格式".to_string()],
        };

        query_result.set(result);
    };

    // 递归查找路径
    fn find_paths(
        value: &Value,
        current_path: String,
        keyword: &str,
        is_key_mode: bool,
        results: &mut Vec<String>,
    ) {
        match value {
            Value::Object(map) => {
                for (k, v) in map {
                    let new_path = format!("{}['{}']", current_path, k);

                    // 如果是查key模式且key匹配
                    if is_key_mode && k == keyword {
                        results.push(new_path.clone());
                    }
                    // 如果是查value模式，继续递归
                    find_paths(v, new_path, keyword, is_key_mode, results);
                }
            }
            Value::Array(arr) => {
                for (i, item) in arr.iter().enumerate() {
                    let new_path = format!("{}[{}]", current_path, i);
                    find_paths(item, new_path, keyword, is_key_mode, results);
                }
            }
            Value::String(s) => {
                if !is_key_mode && s == keyword {
                    results.push(current_path);
                }
            }
            Value::Number(n) => {
                if !is_key_mode && n.to_string() == keyword {
                    results.push(current_path);
                }
            }
            Value::Bool(b) => {
                if !is_key_mode && b.to_string() == keyword {
                    results.push(current_path);
                }
            }
            Value::Null => {
                if !is_key_mode && "null" == keyword {
                    results.push(current_path);
                }
            }
        }
    }

    // 转换为JS风格路径
    let convert_to_js = move |path: &str| -> String {
        let re = Regex::new(r"\['([^']+)'\]").unwrap();
        re.replace_all(path, |caps: &regex::Captures| {
            let key = &caps[1];
            if key.chars().all(|c| c.is_alphanumeric() || c == '_') {
                format!(".{}", key)
            } else {
                format!("[\"{}\"]", key)
            }
        })
        .to_string()
    };

    rsx! {
        div { class: "flex-1 flex flex-col",
            div { class: "flex-1 p-8 overflow-auto",
                div { class: "max-w-4xl mx-auto space-y-6",
                    // 标题和描述
                    div { class: "space-y-2",
                        h1 { class: "text-2xl font-bold text-gray-900", "JSON 路径查找器" }
                        p { class: "text-gray-600", "输入JSON数据，查找键或值并获取完整路径" }
                    }

                    // 输入卡片
                    div { class: "bg-white border border-gray-200 rounded-xl shadow-sm",
                        div { class: "p-6",
                            div { class: "space-y-4",
                                // JSON输入区域
                                div { class: "space-y-2",
                                    label { class: "block text-sm font-medium text-gray-700", "JSON数据" }
                                    textarea {
                                        oninput: move |e| json_input.set(e.value()),
                                        value: {json_input},
                                        class: "w-full h-40 px-3 py-2 border border-gray-300 rounded-lg font-mono text-sm focus:ring-blue-500 focus:border-blue-500",
                                        placeholder: r#"{{"name": "John", "age": 30, "cars": ["Ford", "BMW"]}}"#
                                    }
                                }

                                // 查询条件和操作区
                                div { class: "grid grid-cols-1 md:grid-cols-3 gap-4",
                                    // 查找内容输入
                                    div { class: "space-y-2",
                                        label { class: "block text-sm font-medium text-gray-700", "查找内容" }
                                        input {
                                            r#type: "text",
                                            oninput: move |e| query_input.set(e.value()),
                                            value: "{query_input}",
                                            class: "w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-blue-500 focus:border-blue-500",
                                            placeholder: "输入要查找的内容"
                                        }
                                    }

                                    // 查找模式选择
                                    div { class: "space-y-2",
                                        label { class: "block text-sm font-medium text-gray-700", "查找模式" }
                                        select {
                                            onchange: move |e| query_mode.set(e.value()),
                                            value: "{query_mode}",
                                            class: "
                                                w-full
                                                px-4 py-2
                                                text-sm text-gray-800
                                                bg-white
                                                border border-gray-300
                                                rounded-lg
                                                shadow-sm
                                                transition-all
                                                focus:outline-none
                                                focus:ring-2 focus:ring-blue-500
                                                focus:border-blue-500
                                                hover:border-gray-400
                                                cursor-pointer
                                                appearance-none
                                            ",
                                            for option in query_mode_options.iter() {
                                                option { value: "{option}", "{option}" }
                                            }
                                        }
                                    }

                                    // 操作按钮
                                    div { class: "flex items-end",
                                        button {
                                            onclick: perform_search,
                                            class: " block w-full
                                            px-3 py-2  // 调整内边距
                                            text-sm text-gray-900  // 文字颜色
                                            bg-white  // 背景色
                                            border border-gray-300  // 边框
                                            rounded-lg  // 更大的圆角
                                            shadow-sm  // 轻微阴影
                                            focus:outline-none  // 移除默认轮廓
                                            focus:ring-2 focus:ring-blue-500  // 聚焦光环效果
                                            focus:border-blue-500  // 聚焦边框色
                                            hover:border-gray-400  // 悬停效果
                                            transition-colors  // 颜色过渡动画
                                            appearance-none  // 移除原生样式
                                            [&::-webkit-inner-spin-button]:appearance-none  // 隐藏旋转按钮(Webkit)
                                            [&::-webkit-outer-spin-button]:appearance-none  // 隐藏旋转按钮(Webkit)",
                                            "查找路径"
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // 结果表格
                    if !query_result.read().is_empty() {
                        div { class: "bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden",
                            div { class: "px-6 py-4 border-b border-gray-200",
                                h2 { class: "text-lg font-semibold text-gray-900",
                                    "查找结果: "
                                    span { class: "text-sm font-normal text-gray-500 ml-2",
                                        "共找到 {query_result.read().len()} 条匹配路径"
                                    }
                                }
                            }

                            div { class: "overflow-x-auto",
                                table { class: "min-w-full divide-y divide-gray-200",
                                    thead { class: "bg-gray-50",
                                        tr {
                                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider", "类型" }
                                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider", "Python路径" }
                                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider", "JS路径" }
                                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider", "操作" }
                                        }
                                    }
                                    tbody { class: "bg-white divide-y divide-gray-200",
                                        for path in query_result.read().iter() {
                                            tr { class: "hover:bg-gray-50",
                                                td { class: "px-6 py-4 whitespace-nowrap text-sm text-gray-500",
                                                    if path.contains("['") {
                                                        "对象键"
                                                    } else if path.contains("[") {
                                                        "数组索引"
                                                    } else {
                                                        "值"
                                                    }
                                                }
                                                td { class: "px-6 py-4 whitespace-nowrap font-mono text-sm text-gray-900",
                                                    "{path}"
                                                }
                                                td { class: "px-6 py-4 whitespace-nowrap font-mono text-sm text-gray-900",
                                                    "{convert_to_js(path)}"
                                                }
                                                td { class: "px-6 py-4 whitespace-nowrap text-sm text-gray-500",
                                                    Copy{
                                                        val:path.clone()
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
